﻿using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Timers;
using Message;

namespace Server.Net
{
    public class ServNet
    {
        /// <summary>
        /// 实例
        /// </summary>
        public static ServNet instance;
        /// <summary>
        /// 心跳定时器
        /// </summary>
        Timer hbTimer = new Timer(1000);
        /// <summary>
        /// 心跳超时时间12s
        /// </summary>
        public long heartBeatTime = 12;
        /// <summary>
        /// 位置分发定时器
        /// </summary>
        Timer moveTimer = new Timer(200);

        /// <summary>
        /// 消息分发
        /// </summary>
        public MsgDisPatcher msgDist;
        /// <summary>
        /// 所有在线用户
        /// </summary>
        public Dictionary<int, PlayerSession> Users = new Dictionary<int, PlayerSession>();

        public ServNet()
        {
            instance = this;
            msgDist = new MsgDisPatcher();
        }

        public GameServer gameServer;

        public void Start(int port)
        {
            hbTimer.Elapsed += HandleHBTimer;
            hbTimer.AutoReset = true;
            hbTimer.Enabled = true;

            moveTimer.Elapsed += HandleMoveTimer;
            moveTimer.AutoReset = true;
            moveTimer.Enabled = true;

            gameServer = new GameServer();
            var serverConfig = new ServerConfig
            {
                Port = port, //set the listening port
                Ip = "Any",
                Name = "GameServer",
                //Other configuration options
                Mode = SocketMode.Tcp,
                MaxConnectionNumber = 2000,
                IdleSessionTimeOut = 600,
                TextEncoding = "UTF-8",
                //syncSend: 是否启用同步发送模式, 默认值: false;
                SyncSend = false,
                SendBufferSize = 1024,
                ReceiveBufferSize = 1024,
                LogBasicSessionActivity = true,
                LogAllSocketException = true,
                KeepAliveTime = 300,
            };

            if (gameServer.Setup(serverConfig) == false)
            {
                Console.WriteLine("IpAndEnpoint Set Failed");
                return;
            }

            gameServer.NewSessionConnected += NewSessionConnected;
            gameServer.NewRequestReceived += NewRequestReceived;
            gameServer.SessionClosed += SessionClosed;

            if (gameServer.Start() == false)
            {
                Console.WriteLine("[服务器]启动失败");
                return;
            }
            hbTimer.Start();
            moveTimer.Start();
            Console.WriteLine("[服务器]启动成功");
        }

        /// <summary>
        /// 新的玩家连接
        /// </summary>
        /// <param name="session"></param>
        private void NewSessionConnected(PlayerSession session)
        {
            Console.WriteLine("连接：" + session.RemoteEndPoint);
            session.isUse = true;
            msgDist.Update();
        }

        /// <summary>
        /// 收到玩家发送消息
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestInfo"></param>
        private void NewRequestReceived(PlayerSession session, BinaryRequestInfo requestInfo)
        {
            session.Receive(requestInfo.Key, requestInfo.Body);
            msgDist.Update();
        }
        /// <summary>
        /// 关闭时
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void SessionClosed(PlayerSession session, CloseReason value)
        {
            Console.WriteLine("断开：" + session.RemoteEndPoint);
            session.Close();
            msgDist.Update();
        }

        /// <summary>
        /// 心跳
        /// </summary>
        public void HeartBeat()
        {
            long timeNow = Sys.GetTimeStamp();
            if (Users.Count > 0)
            {
                foreach (PlayerSession session in Users.Values)
                {
                    if (session != null && session.isUse && session.SocketSession.Client != null)
                    {
                        if (timeNow - session.lastTickTime > heartBeatTime)
                        {
                            Console.WriteLine("session.lastTickTime:" + session.lastTickTime + " timeNow:" + timeNow);
                            Console.WriteLine("[心跳引起断开连接]:" + session.LocalEndPoint);
                            session.Close();
                        }
                    }
                }
            }
        }

        public void HandleHBTimer(object sender, ElapsedEventArgs e)
        {
            HeartBeat();

        }

        public void HandleMoveTimer(object sender, ElapsedEventArgs e)
        {
            BroadCastMove();

        }

        /// <summary>
        /// 广播玩家位置
        /// </summary>
        void BroadCastMove()
        {
            if (Users.Count > 0)
            {
                S2CMoves stcms = new S2CMoves();
                //Console.WriteLine(Users.Values.Count);
                foreach (PlayerSession session in Users.Values)
                {
                    if (session != null && session.isUse && session.SocketSession.Client != null)
                    {
                        C2SMove ctsmm = new C2SMove
                        {
                            uid = session.uid,
                            uname = session.uname,
                            x = session.x,
                            y = session.y,
                            z = session.z,
                            angle = session.angle
                        };
                        stcms.moves.Add(ctsmm);
                    }
                }
                foreach (PlayerSession session in Users.Values)
                {
                    if (session != null && session.isUse && session.SocketSession.Client != null)
                    {
                        session.SendObj(stcms);
                    }
                }
            }
        }
    }
}